<!-- src/components/WorkerMarkers.vue -->
<template>
    <div></div>
</template>

<script>
export default {
    name: "WorkerMarkers",
    props: {
        map: {
            type: Object,
            required: true,
        },
        personnelHistoryList: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        return {
            workerMarkers: [], // 检修人员标记数组
            workerWindows: [], // 检修人员信息窗口数组
            openedWindowIndex: null, // 记录当前打开的信息窗口索引
        };
    },
    mounted() {
        this.initWorkerMarkers();
    },
    watch: {
        // 监听人员历史列表的变化
        personnelHistoryList: {
            handler(newVal) {
                console.log("WorkerMarkers 收到人员历史列表——————————————————————————————————————————:", newVal);
                if (newVal && newVal.length > 0) {
                    // 更新现有标记，而不是清除重建
                    this.updateWorkerMarkers();
                }
            },
            deep: true,
        },
    },
    methods: {
        // 更新人员标记
        updateWorkerMarkers() {
            const workers = this.personnelHistoryList || [];

            // 如果还没有初始化标记，则初始化
            if (this.workerMarkers.length === 0) {
                this.initWorkerMarkers();
                return;
            }

            // 当人员数量发生变化时，重新初始化以确保全部绘制
            if (workers.length !== this.workerMarkers.length) {
                console.log("人员数量发生变化，重新初始化标记");
                this.clearMarkers();
                this.initWorkerMarkers();
                return;
            }

            // 更新现有标记的位置
            workers.forEach((worker, index) => {
                const lng = worker.longitude !== undefined ? parseFloat(worker.longitude) : worker.lng;
                const lat = worker.latitude !== undefined ? parseFloat(worker.latitude) : worker.lat;

                if (!lng || !lat || worker.onlineStatus != 1) {
                    return;
                }

                // 更新标记位置
                if (this.workerMarkers[index]) {
                    this.workerMarkers[index].setPosition([lng, lat]);
                }

                // 如果这个窗口是打开的，更新窗口内容和位置
                if (this.openedWindowIndex === index && this.workerWindows[index]) {
                    this.workerWindows[index].setContent(this.getWorkerInfoContent(worker));
                    this.workerWindows[index].setPosition([lng, lat]);
                }
            });
        },

        // 清理旧的标记和窗口
        clearMarkers() {
            this.workerMarkers.forEach(marker => {
                marker.setMap(null);
            });
            this.workerWindows.forEach(window => {
                window.close();
            });
            this.workerMarkers = [];
            this.workerWindows = [];
            this.openedWindowIndex = null;
        },

        // 初始化检修人员标记
        initWorkerMarkers() {
            const workers = this.personnelHistoryList || [];
            if (workers.length === 0) {
                return;
            }

            workers.forEach((worker, index) => {
                // 获取经纬度，支持 longitude/latitude 或 lng/lat
                const lng = worker.longitude !== undefined ? parseFloat(worker.longitude) : worker.lng;
                const lat = worker.latitude !== undefined ? parseFloat(worker.latitude) : worker.lat;

                // 如果没有有效的坐标，跳过此人员，不显示在地图上
                if (!lng || !lat) {
                    console.log(`人员 ${worker.name} 没有坐标信息，跳过显示`);
                    return;
                } else {
                    console.log(`人员 ${worker.name} ************************** 有坐标西悉尼：${lng}, ${lat}`);
                }

                // 创建检修人员标记，使用科技蓝人形图标
                const marker = new AMap.Marker({
                    map: this.map,
                    position: [lng, lat],
                    icon: new AMap.Icon({
                        size: new AMap.Size(40, 40),
                        image: worker.online ? require("@/assets/images/work-green.png") : require("@/assets/images/work-red.png"),
                        imageSize: new AMap.Size(40, 40),
                    }),
                    offset: new AMap.Pixel(-16, -32),
                    title: worker.name,
                });

                // 创建信息窗口
                const infoWindow = new AMap.InfoWindow({
                    offset: new AMap.Pixel(0, -30),
                    content: this.getWorkerInfoContent(worker),
                });

                // 绑定点击事件
                marker.on("click", () => {
                    // 记录打开的窗口索引
                    this.openedWindowIndex = index;
                    infoWindow.open(this.map, marker.getPosition());
                });

                // 监听信息窗口关闭事件
                infoWindow.on("close", () => {
                    // 如果关闭的是当前记录的窗口，清除记录
                    if (this.openedWindowIndex === index) {
                        this.openedWindowIndex = null;
                    }
                });

                // 存储引用
                this.workerMarkers.push(marker);
                this.workerWindows.push(infoWindow);
            });
        },

        // 获取检修人员信息窗口内容（优化版）
        getWorkerInfoContent(worker) {
            const statusText = worker.online ? "在线" : "离线";
            const statusClass = worker.online ? "online" : "offline";

            const statusClassSir = worker.online ? "worker-icon-green" : "worker-icon";

            return `
        <div class="tech-worker-info-container">
          <div class="tech-worker-info-header">
            <div class="${statusClassSir}">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="12" cy="7" r="4" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>

            <div class="tech-worker-title">
              <span>${worker.name || "未知人员"}(${worker.phone || "暂无电话"})</span>
           
              <span class="tech-worker-workno">工单：${worker.workNo || "暂无"}</span>
            </div>
          </div>
        </div>
      `;
        },

        // 更新检修人员位置（模拟实时更新）
        //   updateWorkerPositions() {
        //     const workers = this.personnelHistoryList || [];
        //     workers.forEach((worker, index) => {
        //       // 模拟位置更新（实际应用中应从服务器获取实时位置）
        //       if (worker.online) {
        //         // 只更新在线人员位置
        //         // 获取当前坐标，支持 longitude/latitude 或 lng/lat
        //         const currentLng = worker.longitude !== undefined ? worker.longitude : worker.lng;
        //         const currentLat = worker.latitude !== undefined ? worker.latitude : worker.lat;
        //
        //         const newLng = currentLng + (Math.random() - 0.5) * 0.01;
        //         const newLat = currentLat + (Math.random() - 0.5) * 0.01;
        //
        //         // 更新数据
        //         if (worker.longitude !== undefined) {
        //           worker.longitude = newLng;
        //           worker.latitude = newLat;
        //         } else {
        //           worker.lng = newLng;
        //           worker.lat = newLat;
        //         }
        //
        //         // 更新标记位置
        //         if (this.workerMarkers[index]) {
        //           this.workerMarkers[index].setPosition([newLng, newLat]);
        //
        //           // 如果在线状态改变，更新图标
        //           const currentIcon = this.workerMarkers[index].getIcon();
        //           if (currentIcon && currentIcon.image) {
        //             const shouldUseOnlineIcon = worker.online;
        //             const isUsingOnlineIcon = currentIcon.image.includes("0277bd");
        //
        //             if (shouldUseOnlineIcon !== isUsingOnlineIcon) {
        //               this.workerMarkers[index].setIcon(new AMap.Icon({
        //                 size: new AMap.Size(32, 32),
        //                 image: worker.online
        //                   ? ""
        //                   : "",
        //                 imageSize: new AMap.Size(32, 32)
        //               }));
        //             }
        //           }
        //         }
        //
        //         // 更新信息窗口内容
        //         if (this.workerWindows[index]) {
        //           this.workerWindows[index].setContent(this.getWorkerInfoContent(worker));
        //         }
        //       }
        //     });
        //   }
    },
    beforeDestroy() {
        // 清理人员标记
        this.workerMarkers.forEach(marker => {
            marker.setMap(null);
        });

        // 清理信息窗口
        this.workerWindows.forEach(window => {
            window.close();
        });
    },
};
</script>

<style>
/* 检修人员信息窗口样式 */
.tech-worker-info-container {
    background: linear-gradient(145deg, #0c1e3e, #1a3a6a);
    border-radius: 12px;
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.5), 0 0 20px rgba(33, 150, 243, 0.4), inset 0 0 15px rgba(33, 150, 243, 0.3);
    border: 1px solid rgba(79, 195, 247, 0.5);
    overflow: hidden;
    min-width: 220px;
    transform-style: preserve-3d;
    position: relative;
}

.tech-worker-info-container::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, #4fc3f7, transparent);
}

.tech-worker-info-header {
    background: linear-gradient(90deg, #0277bd, #0288d1);
    color: white;
    padding: 14px 18px;
    font-size: 16px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.tech-worker-title {
    display: flex;
    flex-direction: column;
    gap: 4px;
    line-height: 1.2;
}

.tech-worker-userno,
.tech-worker-workno {
    font-size: 13px;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.85);
}

.worker-icon {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    padding: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 3px solid rgba(223, 6, 6);
    /* 添加闪烁动画 */
    animation: blink 1.5s infinite;
    box-shadow: 0 0 15px rgba(223, 6, 6, 0.7);
}
.worker-icon-green {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    padding: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 3px solid rgb(29, 235, 11);
    /* 添加闪烁动画 */
    animation: blinkG 1.5s infinite;
    box-shadow: 0 0 15px rgba(29, 235, 11, 0.7);
}
/* 定义闪烁动画 */
@keyframes blinkG {
    0% {
        box-shadow: 0 0 15px rgba(29, 235, 11, 0.7);
        border-color: rgba(29, 235, 11, 0.8);
    }
    50% {
        box-shadow: 0 0 25px rgba(29, 235, 11, 1);
        border-color: rgba(29, 235, 11, 1);
    }
    100% {
        box-shadow: 0 0 15px rgba(29, 235, 11, 0.7);
        border-color: rgba(29, 235, 11, 0.8);
    }
}
/* 定义闪烁动画 */
@keyframes blink {
    0% {
        box-shadow: 0 0 15px rgba(223, 6, 6, 0.7);
        border-color: rgba(223, 6, 6, 0.8);
    }
    50% {
        box-shadow: 0 0 25px rgba(223, 6, 6, 1);
        border-color: rgba(223, 6, 6, 1);
    }
    100% {
        box-shadow: 0 0 15px rgba(223, 6, 6, 0.7);
        border-color: rgba(223, 6, 6, 0.8);
    }
}
.tech-worker-info-body {
    padding: 5px;
    background: rgba(12, 30, 62, 0.9);
}

.worker-status {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    border-radius: 8px;
    margin-bottom: 16px;
    font-weight: 600;
    font-size: 15px;
    gap: 8px;
}

.worker-status.online {
    background: rgba(76, 175, 80, 0.15);
    color: #81c784;
    border: 1px solid rgba(76, 175, 80, 0.3);
}

.worker-status.offline {
    background: rgba(158, 158, 158, 0.15);
    color: #bdbdbd;
    border: 1px solid rgba(158, 158, 158, 0.3);
}

.status-indicator {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: currentColor;
    box-shadow: 0 0 8px currentColor;
}

.worker-details {
    display: grid;
    gap: 12px;
}

.detail-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    background: rgba(2, 119, 189, 0.1);
    border-radius: 8px;
    border: 1px solid rgba(79, 195, 247, 0.2);
}

.detail-label {
    color: #90caf9;
    font-size: 14px;
}

.detail-value {
    color: #e3f2fd;
    font-weight: 600;
    font-size: 14px;
    text-shadow: 0 0 6px rgba(79, 195, 247, 0.5);
}
</style>
